/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.dbmapping.persistence;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Administrator
 */
public class DbAccess {

    private static DbAccess instance = new DbAccess();
    private DataSource dataSource;
    private static Logger logger;
    private Properties properties = new Properties();

    private DbAccess() {
        logger = LoggerFactory.getLogger(DbAccess.class);
//        dataSource = setupDataSource();
    }

    public static synchronized DbAccess getInstance() {
        if (instance == null) {
            return new DbAccess();
        } else {
            return instance;
        }
    }

    public Connection getConnection() throws SQLException {
        if (dataSource == null) {
            dataSource = setupDataSource();
        }

        Connection conn = dataSource.getConnection();
//        if (conn != null && !conn.isClosed()) {
//            conn.setAutoCommit(false);
//        }
//        logger.trace("[DB] Got connection {}", conn.hashCode());
        return conn;
    }

    private DataSource setupDataSource() {
        try {
            logger.info("Setting up datasource");
            //            String jdbcUrl = "jdbc:mysql://localhost:3306/cbcdb?zeroDateTimeBehavior=convertToNull";
            //            String userName = "root";
            //            String password = "123456";
            //            String classDriverName = "com.mysql.jdbc.Driver";
            String url = properties.getProperty("url", "jdbc:oracle:thin:@192.168.6.248:1521:mca");
            String classDriverName = properties.getProperty("classDriverName", "oracle.jdbc.OracleDriver");
            String user = properties.getProperty("user", "livescreen");
            String password = properties.getProperty("password", "livescreen");

            ComboPooledDataSource cpds = new ComboPooledDataSource();
            cpds.setProperties(properties);
            cpds.setDriverClass(classDriverName); //loads the jdbc driver            
            cpds.setJdbcUrl(url);
            cpds.setUser(user);
            cpds.setPassword(password);
            return cpds;
        } catch (Exception ex) {
            logger.error("", ex);
            return null;
        }
    }

    public static void closeConnection(Connection cn) {
//        logger.trace("[DB] Closing connection");
        if (cn != null) {
            try {
                if (!cn.isClosed()) {
                    cn.close();
//                    logger.trace("[DB] Connection closed: {}", cn.hashCode());
                }
            } catch (SQLException ex) {
                logger.error("", ex);
            }
        }
    }

    public static void commitTransaction(Connection cn) {
        try {
            cn.commit();
        } catch (SQLException ex) {
            logger.error("", ex);
        }
    }

    public static void rollBackTransaction(Connection cn) {
        try {
            cn.rollback();
        } catch (SQLException ex) {
            logger.error("", ex);
        }
    }

    public static void closeConn(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
                logger.error("", ex);
            }
        }
    }

    public static void closePreparedStatement(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception ex) {
                logger.error("", ex);
            }
        }
    }

    public static void closeCallableStatement(CallableStatement cs) {
        if (cs != null) {
            try {
                cs.close();
            } catch (Exception ex) {
                logger.error("", ex);
            }
        }
    }

    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                logger.error("", ex);
            }
        }
    }

    public static void closeStatement(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception ex) {
                logger.error("", ex);
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        DataSources.destroy(dataSource);
        logger.debug("DB Connection Pool destroyed");
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
        dataSource = setupDataSource();
    }

    public void enableMonitor(ScheduledExecutorService executor, long initialDelay, long period) {
        MonitorTask monitorTask = new MonitorTask();
        executor.scheduleAtFixedRate(monitorTask, initialDelay, period, TimeUnit.MILLISECONDS);
    }

    private class MonitorTask implements Runnable {

        @Override
        public void run() {
            if (dataSource != null) {
                try {
                    ComboPooledDataSource cpds = (ComboPooledDataSource) dataSource;
                    Map<String, Object> statisticMap = new TreeMap<String, Object>();
                    statisticMap.put("maxPoolSize", cpds.getMaxPoolSize());
                    statisticMap.put("minPoolSize", cpds.getMinPoolSize());
                    statisticMap.put("numBusyConnections", cpds.getNumBusyConnectionsDefaultUser());
                    statisticMap.put("numConnections", cpds.getNumConnectionsDefaultUser());
                    statisticMap.put("numIdleConnections", cpds.getNumIdleConnectionsDefaultUser());

                    Set<String> keySet = statisticMap.keySet();
                    StringBuilder sb = new StringBuilder();
                    for (String key : keySet) {
                        sb.append(key).append(": ").append(statisticMap.get(key)).append(" | ");
                    }
                    logger.debug("Db Statistic: {}", sb.toString());
                } catch (SQLException ex) {
                    logger.error("Error checking DB connection statistic: ", ex);
                }
            }
        }
    }
}
